package myface;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

import com.google.gson.Gson;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;
/**
 * 人脸引擎的websocket实时通知通道
 */
public class EmptyClient extends WebSocketClient {
    // public BufferedImage previewImage;
    public Image previewImage;

	long lastTime;

	JLabel imgLbl;
	public EmptyClient(URI serverUri, Draft draft) {
		super(serverUri, draft);
	}

	public EmptyClient(URI serverURI) {
		super(serverURI);
	}

	@Override
	public void onOpen(ServerHandshake handshakedata) {
		send("Hello, it is me. Mario :)");
		System.out.println("new connection opened");
	}

	@Override
	public void onClose(int code, String reason, boolean remote) {
		System.out.println("closed with exit code " + code + " additional info: " + reason);
	}

	@Override
	public void onMessage(String message) {
		// System.out.println("received message: " + message);
          Gson gson = new Gson();
          HashMap map = gson.fromJson(message,HashMap.class);
        //   System.out.println(map.get("method"));
          if(map.get("method").equals("face.updateUI")){
            // if (lastTime + 60 > new Date().getTime()) {
            //   return;
            // }
            // System.out.println("received message: " +new Date().getTime());
            lastTime = new Date().getTime();
            Map payload = (Map) map.get("payload");
            // 转换base64图片数据
            final String base64Image =(String) payload.get("image"); 
            byte[] imageByte = Base64.getDecoder().decode(base64Image);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            try {
              BufferedImage tmp = ImageIO.read(bis);
              if(imgLbl!=null){
                previewImage = tmp.getScaledInstance(imgLbl.getWidth(), imgLbl.getHeight(), tmp.getType());
                imgLbl.repaint();
              }
            } catch (IOException e) {
              e.printStackTrace();
            }
          }

	}

	@Override
	public void onMessage(ByteBuffer message) {
		System.out.println("received ByteBuffer");
	}

	@Override
	public void onError(Exception ex) {
		System.err.println("错误czj：an error occurred:" + ex);
        EmptyClient self = this;
        if(ex.getMessage().contains("Connection refused")){
		    System.err.println("错误从新链接");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SwingUtilities.invokeLater(()->{
               self.reconnect(); 
            });
        }
	}

}
